package dao

import (
	"fmt"
	"goWeb/bookStore/model"
	"goWeb/bookStore/utils"
)

func AddCartItem(ct *model.CartItem) (err error) {
	sqlstr := "insert into cart_items (count,amout,cart_id,book_id) values(?,?,?,?)"
	//	fmt.Printf("添加Cartietm的时候，参数分别为%v %v %v %v \n", ct.Count, ct.GetAmout(), ct.CartId, ct.Books.Id)

	_, err = utils.Db.Exec(sqlstr, ct.Count, ct.GetAmout(), ct.CartId, ct.Books.Id)
	if err != nil {
		fmt.Println("添加cartitem失败", err)
	}
	return err
}

//根据bookid来查找购物车细项
func GetCartItemByBookIdAndCartId(bookid string, cartid string) (ci *model.CartItem, err error) {
	sqlstr := "select id,count,amout,cart_id,book_id from cart_items where book_id=? and cart_id=?"
	row := utils.Db.QueryRow(sqlstr, bookid, cartid)
	ci = &model.CartItem{}
	var book_id int
	//fmt.Println("row=", row)
	err = row.Scan(&ci.Id, &ci.Count, &ci.Amout, &ci.CartId, &book_id)
	if err != nil {
		return nil, err
	}

	book := GetBookById(book_id)
	ci.Books = book
	return ci, nil
}

//更新购物项的count
func UpdateCartItemCount(ct *model.CartItem) (err error) {
	sqlstr := "update cart_items set count=?,amout=? where cart_id=? and book_id=?"
	_, err = utils.Db.Exec(sqlstr, ct.Count, ct.GetAmout(), ct.CartId, ct.Books.Id)
	return
}

//根据cartid来查找购物车细项
func GetCartItemByCartId(cartid string) (cis []*model.CartItem, err error) {
	sqlstr := "select id,count,amout,cart_id,book_id from cart_items where cart_id=?"
	rows, err := utils.Db.Query(sqlstr, cartid)
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		var book_id int
		ci := &model.CartItem{}

		err = rows.Scan(&ci.Id, &ci.Count, &ci.Amout, &ci.CartId, &book_id)
		book := GetBookById(book_id)
		ci.Books = book
		if err != nil {
			return nil, err
		}
		cis = append(cis, ci)
	}
	return cis, nil

}

//根据cartid删除购物项
func DelCartItemByCartId(cartid string) (err error) {
	sqlstr := "delete from cart_items where cart_id=?"
	_, err = utils.Db.Exec(sqlstr, cartid)
	return err
}

//根据id删除购物项
func DelCartItemById(id string) (err error) {
	sqlstr := "delete from cart_items where id=?"
	_, err = utils.Db.Exec(sqlstr, id)
	return err
}
